import axios from 'axios'

// 登录完成后的所有请求必须在请求的headers中添加token
let axiosIns = axios.interceptors.request.use(
  function (config) {
    let loginToken = sessionStorage.getItem('LoginToken')
    // alert('token is ' + loginToken)
    if (loginToken) {
      config.headers.Authorization = `Bearer ${loginToken}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)
export default {
  async login (data) {
    let result = await axios({
      url: '/api/login',
      method: 'post',
      // 个人认为请求头应该就是关键
      // headers: { 'Content-Type': 'application/json;charset=utf-8' },
      // transformRequest: (data) => JSON.stringify(data),
      data: data
    })
    return result
  },
  async logout () {
    // 退出登录时，取消全局注册的钩子
    // 把header中的token清除掉
    axios.interceptors.request.eject(axiosIns)
  },
  async getUserProgress () {
    let result = await axios({
      url: '/api/getuserprogress',
      method: 'get'
    })
    // alert('monthPercent=' + result.data.monthPercent + 'shops=' + result.data.totalShops)
    return result
  }
}
